//
//  VC1.m
//  ObjcCodable
//
//  Created by chenbo on 2025/2/10.
//

#import "VC1.h"
#import "UITableView+Reuse.h"
#import "TCell1.h"
#import "ObjcCodable-Swift.h"
#import "DataSourceTool.h"

@interface VC1 ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) GiftsResp *resp;

@end

@implementation VC1

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSStringFromClass([self class]);
    self.view.backgroundColor = UIColor.lightGrayColor;
    [self setupUI];
    [self fetchData];
}

- (void)setupUI {
    self.tableView = [[UITableView alloc] init];
    [self.view addSubview:self.tableView];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    [[self.tableView.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:100] setActive:YES];
    [[self.tableView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor] setActive:YES];
    [[self.tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor] setActive:YES];
    [[self.tableView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor] setActive:YES];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
}

- (void)fetchData {
    NSDictionary *resp = [DataSourceTool readLocalFileWithName:@"gifts"];
    
    GiftsResp *res = [GiftsResp instanceWithJsonObject:resp];
    self.resp = res;
    NSLog(@"res is: %@", res);
    NSLog(@"jsonDict is: %@", self.resp.jsonObject);
    NSLog(@"jsonString is: %@", self.resp.jsonString);
    
    NSArray *listResp = [DataSourceTool readLocalFileWithName:@"list"];
    NSArray<List *> *list = [List arrayFrom:listResp];
    List *item = list[0];
    NSLog(@"list: %@", item.name);
    NSArray <User *> *users = [User arrayFrom:listResp];
    
}

- (void)setResp:(GiftsResp *)resp {
    _resp = resp;
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource && UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.resp.data.list) {
        return 0;
    }
    return self.resp.data.list.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    List *md = self.resp.data.list[indexPath.row];
    TCell1 *cell = [tableView dequeueReusableCellWithNibClass:TCell1.class];
    cell.titleLabel.text = md.name;
    cell.subTitleLabel.text = md.price;
    cell.descLabel.text = md.memoNames.cn;
    return cell;
}

@end
